import { SinatureDataResponse } from "@/apis/upload";
import { getSignatureData, uploadFileByFormData } from "@/apis/upload";

// 生成文件名，作为 key 使用
export const generateFileName = (
  signatureData: SinatureDataResponse,
  file: File
) => {
  const suffix = file.name.slice(file.name.lastIndexOf("."));
  const filename = Date.now() + suffix;
  return signatureData.dir + filename;
};

interface FileUploadResult {
  url: string;
  fileName: string;
  size: number;
  type: string;
}

// 上传资源文件
export const upload = async (
  file: File
): Promise<[boolean, FileUploadResult]> => {
  const result = {
    url: "",
    fileName: file?.name || "",
    size: file?.size || 0,
    type: file?.type || "",
  };
  if (!file) return [false, result]; // 返回一个空对象作为默认 result

  let signatureData = JSON.parse(localStorage.getItem("signature") || "{}");
  console.log("签证过期", signatureData?.expire < Date.now() / 1e3);

  // 如果签名数据不存在或者已经过期，重新获取
  if (
    !Object.keys(signatureData).length ||
    signatureData?.expire < Date.now() / 1e3
  ) {
    const [success, ossData] = await getSignatureData();
    if (success) {
      localStorage.setItem("signature", JSON.stringify(ossData));
      signatureData = ossData;
    } else {
      return [false, result]; // 获取签名失败
    }
  }

  const fileName = generateFileName(signatureData, file);
  const formdata = new FormData();
  formdata.append("key", fileName);
  formdata.append("OSSAccessKeyId", signatureData.accessId);
  formdata.append("policy", signatureData.policy);
  formdata.append("Signature", signatureData.signature);
  formdata.append("success_action_status", "200");
  formdata.append("file", file);

  const [uploadSuccess] = await uploadFileByFormData(
    signatureData.host,
    formdata
  );

  if (uploadSuccess) {
    result.url = `${signatureData.host}/${fileName}`;
    return [true, result];
  }

  return [false, result]; // 上传失败
};
